package com.solo.system.service.impl;

import com.solo.common.core.base.service.impl.BasicServiceImpl;
import com.solo.common.core.utils.collection.CollUtils;
import com.solo.system.api.entity.SysRoleMenu;
import com.solo.system.mapper.SysRoleMenuMapper;
import com.solo.system.model.role.SysRoleMenuConvert;
import com.solo.system.model.role.req.RoleMenuReq;
import com.solo.system.service.SysRoleMenuService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 角色菜单关联 Service实现类
 * @author 十一
 * @since 2023-12-25 16:57
 * 人生若只如初见，何事秋风悲画扇
 **/
@Service
@AllArgsConstructor
public class SysRoleMenuServiceImpl extends BasicServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService {

    private final SysRoleMenuMapper sysRoleMenuMapper;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean assignMenu(RoleMenuReq req) {
        // 删除旧的角色菜单关联
        sysRoleMenuMapper.deleteByRoleIds(Collections.singleton(req.getRoleId()));
        
        Set<Long> menuIds = req.getMenuIds();
        if (CollUtils.isEmpty(menuIds)) {
            return Boolean.TRUE;
        }
        // 批量保存新的角色菜单关联
        return saveBatch(SysRoleMenuConvert.INSTANCE.convert(req));
    }

    @Override
    public Set<Long> selectMenuIds(Long roleId) {
        List<Long> menuIds = sysRoleMenuMapper.selectMenuIdsByRoleId(roleId);
        return new HashSet<>(menuIds);
    }

}